package cn.aj.aop;

import cn.aj.org.domain.SysLog;
import cn.aj.org.mapper.SysLogMapper;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.util.Date;

@Component
@Aspect
@Slf4j
public class LogManager {
    @Autowired
    private SysLogMapper sysLogMapper;

    /**
    * @Description: TODO
    * @Author: aj
    * @Version: 1.0
    * @Date:  2022/11/9 0009 13:26
     * 定义一个空方法,也就是我们的切点
    */
    @Pointcut("@annotation(cn.aj.aop.LogAop)")
    public void pointcut() {}

    /**
    * @Description: TODO
    * @Author: aj
    * @Version: 1.0
    * @Date:  2022/11/9 0009 13:31
     * 需要的参数 id 获取注解上面的name属性 获取方法的名字 电脑ip
    */
    @Around("pointcut()")
    public Object around(ProceedingJoinPoint pjp) throws Throwable {
        //
        MethodSignature methodSignature = (MethodSignature) pjp.getSignature();
        Method method = methodSignature.getMethod();
        // 获取注解
        LogAop annotation = method.getAnnotation(LogAop.class);
        // 获取注解上面的name字段
        String name = annotation.name();
        // 日志打印注解上面name的字段
        log.info("获取注解上面的name字段的值{}", name);
        // 获取方法名称
        String methodName = method.getName();
        log.info("获取方法名{}", methodName);
        // 获取电脑ip
        InetAddress localHost = Inet4Address.getLocalHost();
        // 电脑ip
        String hostAddress = localHost.getHostAddress();
        log.info("获取电脑ip{}", hostAddress);
        // 调用方法,获取所有的方法
        Object proceed = pjp.proceed();
        // 设置值
        SysLog sysLog = new SysLog();
        sysLog.setName(name);
        sysLog.setMethodName(methodName);
        sysLog.setHostAddress(hostAddress);
        sysLog.setCrateTime(new Date());
        // 调用方法保存到数据库
        sysLogMapper.add(sysLog);
        return proceed;
    }
}
